#include "chatdialog.h"
#include "ui_chatdialog.h"

ChatDialog::ChatDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ChatDialog)
{
    ui->setupUi(this);

    m_sock = new QTcpSocket(this);

    connect(m_sock, &QTcpSocket::connected, this, &ChatDialog::connectSuccess);
    connect(m_sock, &QTcpSocket::readyRead, this, &ChatDialog::recvMsg);
    connect(m_sock, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &ChatDialog::errorHandle);

    ui->edtRecord->appendPlainText("[系统] 正在连接服务器，请稍候...\n\n");
    m_sock->connectToHost("39.102.215.47", 8879);

}

ChatDialog::~ChatDialog()
{
    delete ui;
}

void ChatDialog::connectSuccess()
{
    ui->edtRecord->appendPlainText("[系统]连接服务器成功！ \n\n");
    ui->btnSend->setEnabled(true);
}

void ChatDialog::errorHandle(QAbstractSocket::SocketError socketError)
{

    ui->edtRecord->appendPlainText("[系统]连接服务器失败！ \n\n");
    ui->btnSend->setEnabled(false);
}


void ChatDialog::recvMsg()
{
    QByteArray data = m_sock->readAll();

    ui->edtRecord->appendPlainText(QString::fromUtf8(data));
}


void ChatDialog::on_btnSend_clicked()
{
    QString msg = ui->edt->toPlainText();

    m_sock->write(msg.toUtf8());
}
